import { defineStore } from "pinia";
import { reqPost } from "../common/http.request";
import { uToast } from "../utils/uniUtils";
import { useUser } from "./useUser";

export const useShop = defineStore("shop", {
  state: () => ({
    cart: [],
    lock: false,
  }),
  getters: {
    tCount(state) {
      return state.cart.reduce((p, c) => p + c.FQty, 0);
    },
    tMoney(state) {
      return state.cart.reduce((p, c) => p + c.FQty * c.FPrice, 0);
    },
  },
  actions: {
    async SetShoppingCart(goods_id, delta) {
      if (this.lock) {
        return;
      }
      try {
        this.lock = true;

        let qty = this.cart.some((l) => l.FItemID == goods_id)
          ? this.cart.find((l) => l.FItemID == goods_id).FQty + delta
          : 1;
        await reqPost("SetShoppingCart", {
          goods_id,
          qty,
        });
      } catch (e) {
        console.log("error-->", e);
      } finally {
        await this.GetShoppingCart();
        this.lock = false;
      }
    },
    async AddToCart(goods_id, price = 99999) {
      if (this.lock) {
        return;
      }

      try {
        this.lock = true;
        // await this.GetShoppingCart();
        let qty = this.cart.some((l) => l.FItemID == goods_id)
          ? this.cart.find((l) => l.FItemID == goods_id).FQty + 1
          : 1;
        const res = await reqPost("AddCart", {
          goods_id,
          qty,
          price,
        });
        await this.GetShoppingCart();
        if (res.Data) {
          uToast("添加购物车成功！");
        }
      } catch (e) {
        console.log("error-->", e);
      } finally {
        this.lock = false;
      }
    },
    async MinusToCart(goods_id) {
      if (this.lock) {
        return;
      }

      try {
        this.lock = true;
        // await this.GetShoppingCart();
        let qty = 0;
        if (this.cart.some((l) => l.FGoodsID == goods_id)) {
          qty = this.cart.find((l) => l.FGoodsID == goods_id).FQty - 1;
        } else {
          uToast("商品不存在！", "error");
          return;
        }
        if (qty > 0) {
          await reqPost("UpCart", {
            goods_id,
            qty,
          });
        } else {
          let FEntryID = this.cart.find((l) => l.FGoodsID == goods_id).FEntryID;
          await reqPost("DelCartGoods", {
            FEntryID,
          });
        }
      } catch (e) {
        console.log("error-->", e);
      } finally {
        await this.GetShoppingCart();
        this.lock = false;
      }
    },
    async GetShoppingCart() {
      const hasLogin = useUser().hasLogin;
      if (hasLogin) {
        const { Data } = await reqPost("GetShopCart", {});
        this.cart = Data;
        console.log(this.cart, "cart");
      }
    },
    ClearCart: async function () {
      const hasLogin = useUser().hasLogin;
      if (hasLogin) {
        const { Data } = await reqPost("DelCart", {});
        await this.GetShoppingCart();
        return Data;
      }
    },
  },
});
